package cn.z2huo.knowledge.concurrency.countdownlatch.demo2;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *
 * @author z2huo
 */
class Driver {

    private static final int N = 100;

    static class Person implements Runnable {

        private final CountDownLatch countDownLatch;

        private final int i;

        public Person(CountDownLatch countDownLatch, int i) {
            this.countDownLatch = countDownLatch;
            this.i = i;
        }

        @Override
        public void run() {
            try {
                System.out.println("Person " + i + " is ready");
                // 倒计时门闩减 1
                countDownLatch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(N);

        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < N; i++) {
            threadPool.execute(new Person(latch, i));
        }

        System.out.println(latch.getCount());
        try {
            // 等待倒数门闩计数值变为 0
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("end");
        threadPool.close();
    }

}
